package store.core;

import day0301.MyListIndexOutOfBoundsException;
import store.model.*;
import store.util.MyList;

import java.util.Scanner;

/**
 * 开发喵store
 *
 * @version 1.0
 */
public class Store {

    /**
     * 管理员列表
     */
    private static MyList adminList;

    /**
     * 会员列表
     */
    private static MyList vipList;


    /**
     * 商品列表
     */
    private static MyList goodsList;


    /**
     * 商品分类
     */
    private static MyList categoryList;

    /**
     * 会员等级
     */
    private static MyList levelList;

    // 当前登录用户
    private Account currentUser;

    static {
        vipList = new MyList(5);
        adminList = new MyList(1);
        goodsList = new MyList(5);
        categoryList = new MyList(3);
        levelList = new MyList(5);
    }

    /**
     * Scanner 对象
     * final 修饰的变量叫做常量,命名时每个单词都大写,单词间使用下划线(_)连接
     */
    private static final Scanner INPUT = new Scanner(System.in);

    public Store() {
        // 模拟已有数据
        Admin admin = new Admin("123", "123", "管理员");
        adminList.add(admin);


        categoryList.add(new Category(1, "零食"));
        categoryList.add(new Category(2, "蔬菜"));
        categoryList.add(new Category(3, "水果"));
        categoryList.add(new Category(4, "酒水"));

        goodsList.add(new Goods("a1001", "火腿肠", 0.5, 2.5, 50, (Category) categoryList.getElement(0)));
        goodsList.add(new Goods("a1002", "薯片", 1.5, 3.5, 30, (Category) categoryList.getElement(0)));
        goodsList.add(new Goods("b2001", "萝卜", 0.8, 1.5, 50, (Category) categoryList.getElement(1)));
        goodsList.add(new Goods("b2002", "白菜", 0.2, 0.8, 50, (Category) categoryList.getElement(1)));
        goodsList.add(new Goods("c3001", "车厘子", 30, 50, 50, (Category) categoryList.getElement(2)));
        goodsList.add(new Goods("c3002", "芒果", 5, 8, 50, (Category) categoryList.getElement(2)));
        goodsList.add(new Goods("d4001", "五粮液", 1350, 1700, 60, (Category) categoryList.getElement(3)));
        goodsList.add(new Goods("d4002", "飞天茅台", 1800, 2500, 60, (Category) categoryList.getElement(3)));

        levelList.add(new Level("普通会员", 0, 1));
        levelList.add(new Level("黄金会员", 1000, 0.9));
        levelList.add(new Level("铂金会员", 3000, 0.85));
        levelList.add(new Level("钻石会员", 10000, 0.75));
        levelList.add(new Level("黑金会员", 50000, 0.7));

        // 模拟 会员账号
        Vip vip = new Vip("111", "111", "张三", (Level) levelList.getElement(0));
        vipList.add(vip);

        vip = new Vip("222", "222", "李四", (Level) levelList.getElement(0));
        vipList.add(vip);
    }

    public void open() {
        // 打印欢迎语
        welcome();
        // 首页功能列表
        indexMenuList();
    }

    /**
     * 打印欢迎语
     */
    private void welcome() {
        println("*******************************************");
        println("*                                         *");
        println("*          欢迎光临 开发喵Store             *");
        println("*                                         *");
        println("*******************************************");
        println("  (请根据提示输入相应的编号使用本系统) ");
    }

    /**
     * 首页功能列表
     */
    private void indexMenuList() {
        println("1. 会员登录");
        println("2. 注册");
        println("3. 管理员登录");
        println("0. 退出");
        print("请选择：");
        int in = INPUT.nextInt();
        router(in);
    }

    /**
     * 管理员 菜单
     * 20x  20x
     * 200 + in
     */
    public void adminMenuList() {
        println("1. 会员信息");
        println("2. 商品入库");
        println("3. 新增商品分类");
        println("4. 商品列表");
        println("0. 退出");
        print("请选择：");
        int in = INPUT.nextInt();
        // 如果是 0 不变，如果不是 管理员路由 要加 200
//        in = in + in == 0? 0 : 200;
        if (in != 0) {
            in += 200;
        }
        router(in);
    }


    /**
     * 功能跳转
     *
     * @param in
     */
    private void router(int in) {
        switch (in) {
            case 1 -> login();
            case 2 -> register();
            case 3 -> adminLogin();
            case 201 -> showVipList();
            case 202 -> addGoods();
            case 203 -> addCategory();
            case 204 -> {
                showGoodsList();
                adminMenuList();
            }
            case 0 -> exit();
            default -> {
                print("输入错误，请重新输入:");
                router(INPUT.nextInt());
            }
        }
    }

    private void showGoodsList() {
        println("商品列表如下：");
        if (currentUser instanceof Vip) {
            for (int i = 0; i < goodsList.size(); i++) {
                Goods element = (Goods) goodsList.getElement(i);
                if (element.getCount() > 0) {
                    println(element.show());
                }
            }
        } else {
            println(goodsList.toString());
        }
    }

    public void showCategory() {
        String categorys = categoryList.toString();
        println("现有商品分类如下：");

        if ("".equals(categorys)) {
            println("(暂无商品分类)");
        } else {
            println(categorys);
        }
    }

    /**
     * 新增商品分类
     */
    private void addCategory() {

        showCategory();

        print("请输入分类编号：");
        int no = INPUT.nextInt();
        print("请输入分类名称:");
        String name = INPUT.next();

        Category category = new Category(no, name);

        categoryList.add(category);

        adminMenuList();
    }

    /**
     * 商品入库
     */
    private void addGoods() {
        print("请输入商品编号：");
        String no = INPUT.next();

        Goods goods = null;
        // 有没有库存
        for (int i = 0, length = goodsList.size(); i < length; i++) {
            Object element = goodsList.getElement(i);
            if (element instanceof Goods goods1) {
                if (goods1.getGoodNo().equals(no)) {
                    goods = goods1;
                }
            }
        }

        if (goods == null) {
            // 新入库
            goods = new Goods();
            goods.setGoodNo(no);

            print("请输入商品名称：");
            String goosName = INPUT.next();
            goods.setGoodsName(goosName);

            print("请输入商品进价：");
            double cost = INPUT.nextDouble();
            goods.setCost(cost);

            print("请输入商品售价：");
            double price = INPUT.nextDouble();
            goods.setPrice(price);

            showCategory();
            print("请选择商品分类：");
            int category = INPUT.nextInt();

            for (int i = 0; i < categoryList.size(); i++) {
                Object element = categoryList.getElement(i);

                if (element instanceof Category category1) {
                    if (category1.getNo() == category) {
                        goods.setCategory(category1);
                        break;
                    }
                }
            }
        }

        print("请输入商品数量：");
        int count = INPUT.nextInt();
        goods.setCount(goods.getCount() + count);

        goodsList.add(goods);

        println("添加商品成功!");

        adminMenuList();
    }

    /**
     * 管理员登录
     */
    private void adminLogin() {
        print("请输入电话号：");
        String phone = INPUT.next();
        print("请输入密码：");
        String password = INPUT.next();

        Admin login = new Admin(phone, password, null);

        Account flag = checkAccount(login, adminList);

        if (flag instanceof Admin admin) {
            login = admin;
        }

        if (flag != null) {
            currentUser = login;
            // 登录成功
            println(login.getName() + ", 欢迎您！");
            adminMenuList();
        } else {
            // 失败
            println("账号或密码错误，请重试!");
            indexMenuList();
        }
    }

    /**
     * 检测账号是否正确
     *
     * @param account
     * @param list
     * @return
     */
    private Account checkAccount(Account account, MyList list) {
        for (int i = 0; i < list.size(); i++) {
            Object element = list.getElement(i);

            if (element instanceof Account account1) {
                if (account.login(account1)) {
                    return account1;
                }
            }
        }
        return null;
    }

    /**
     * 显示所有会员信息
     */
    private void showVipList() {
        println("现在共有 " + vipList.size() + " 名会员. 信息如下：");
        println(vipList.toString());
    }


    /**
     * 添加会员信息
     *
     * @param vip
     * @return
     */
    public static boolean addVip(Vip vip) {
        return vipList.add(vip);
    }

    /**
     * 退出系统
     */
    private void exit() {
        println("欢迎下次光临！");
        System.exit(0);
    }

    /**
     * 注册
     */
    private void register() {
        println("注册：根据提示输入会员信息.");
        print("请输入手机号：");
        String phone = INPUT.next();
        // TODO( 校验是否已注册 )
//        for (int i = 0; i < vipList.size(); i ++) {
//            Object element = vipList.getElement(i);
//            if (element instanceof Vip vip) {
////                phone.equals(vip.getPhone())
//            }
//        }
        String pwd = null;
        do {
            print("请输入密码：");
            pwd = INPUT.next();
            print("请再次输入密码：");
            String pwd2 = INPUT.next();
            if (!pwd.equals(pwd2)) {
                println("两次密码不一致，请重新输入！");
            } else {
                break;
            }
        } while (true);

        print("请输入会员姓名：");
        String name = INPUT.next();

        // 将会员信息保存
        Vip vip = new Vip(phone, pwd, name);
        addVip(vip);

        println(name + ", 恭喜您称为本店的会员！");
        // 回到上一级
        indexMenuList();
    }

    /**
     * 登录
     */
    private void login() {
        print("请输入电话号：");
        String phone = INPUT.next();
        print("请输入密码：");
        String password = INPUT.next();

        Vip login = new Vip(phone, password, null);

        Account flag = checkAccount(login, vipList);

        if (flag instanceof Vip vip) {
            login = vip;
        }

        if (flag != null) {
            currentUser = login;
            currentUser.setShopCar(new MyList(1));
            // 登录成功
            println(login.getName() + ", 欢迎您！");
            shopping();
            // 结账
            pay();
        } else {
            // 失败
            println("账号或密码错误，请重试!");
            indexMenuList();
        }
    }

    private void shopping() {
        showGoodsList();
        print("请选择您要购买的商品：");
        // TODO(判断输入有效性)
        String no = INPUT.next();

        int index = goodsList.search(new Goods(no));
        Goods goods = null;
        try{
            goods = (Goods) goodsList.getElement(index);
        } catch (MyListIndexOutOfBoundsException exception) {
            throw new RuntimeException("购买商品时出错", exception);
        }

        print("请输入购买 【" + goods.getGoodsName() + "】 的数量：");
        int count = INPUT.nextInt();
        while (goods.getCount() < count) {
            // 库存不够
            println("对不起，库存不足。请重新输入：");
            count = INPUT.nextInt();
        }

        // 加购物车
        currentUser.getShopCar().add(new Treasure(goods, count));

        print("是否继续购物？ 1. 继续购物  2. 结账");
        int t = INPUT.nextInt();
        if (t == 1) {
            shopping();
        }
        return;
    }

    private void pay() {
        println("您本次的购物清单是：");
        MyList shopCar = currentUser.getShopCar();
        println("序号\t商品名称\t单价\t数量\t小计");
        double sum = 0;
        for (int i = 0; i < shopCar.size(); i++) {
            Treasure element = (Treasure) shopCar.getElement(i);
            sum += element.getSum();
            println((i + 1) + "\t" + element);
        }
        println("总计： " + sum + "元");

        double in = sum;
        if (currentUser instanceof Vip vip) {
            Level level = vip.getLevel();
            in = level.getDiscount() * sum;
            println("您是尊贵的 【" + level.getName() + "】" + "本次购物打折后应收：" + in);
            double money = 0.0;
            do{
                print("收款：");
                money = INPUT.nextDouble();
                if (money < in){
                    println("付款金额不足，请重新支付.");
                } else {
                    break;
                }
            } while (true);


            println("找零：" + (money - in));

            // 修改商品库存
            for (int i = 0; i < shopCar.size(); i++) {
                Treasure element = (Treasure)shopCar.getElement(i);

                Goods goods = element.getGoods();
                goods.setCount(goods.getCount() - element.getNum());
            }

            // 积分
            int point = (int) Math.floor(in);
            vip.setPoint(vip.getPoint() + point);

            // 能否升级会员
            for (int i = levelList.size() - 1; i >= 0; i--) {
                Level element = (Level) levelList.getElement(i);
                if (element.getBase() < vip.getPoint()) {
                    // 符号当前等级
                    if (!element.getName().equals(vip.getLevel().getName())) {

                        vip.setLevel(element);
                        println("恭喜您，升级为本店的 【" + element.getName() + "】, 以后购物可享" + (int)(element.getDiscount() * 10) + "折");
                        break;
                    }
                    break;
                }
            }
        }
        logout();
    }

    public void logout() {
        println("欢迎下次光临！");
        currentUser = null;
        indexMenuList();
    }

    /**
     * 控制台打印封装
     *
     * @param str 打印内容
     */
    public static void println(String str) {
        System.out.println(str);
    }

    public static void print(String str) {
        System.out.print(str);
    }
}
